/*
 * Copyright (C) 2015 Kenji Le
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package glamourbeautyclinic;

import glamourbeautyclinic.customer.FrmCustomer;
import images.GlamourImage;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import util.DBConnection;

/**
 *
 * @author Kenji Le
 */
public class FrmChangePass extends javax.swing.JInternalFrame {
    
    GlamourImage GI = new GlamourImage();
    DBConnection dc;
    ArrayList param = new ArrayList();
    String User;
    
    /**
     * Creates new form FrmChangePass
     */
    public FrmChangePass(DBConnection dc) {
        initComponents();
        
        GI.addIconFor(this);
        this.dc = dc;
        
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((screenSize.width - this.getWidth()) / 2, (screenSize.height - this.getHeight()-60) / 2);
    }
    
    private void getAuthority() {
        if (User == null) {
            try {
                User = (String)getDesktopPane().getTopLevelAncestor().getClass().getDeclaredField("user").get(getDesktopPane().getTopLevelAncestor());
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(FrmCustomer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblOldPass = new javax.swing.JLabel();
        txtOldPass = new javax.swing.JPasswordField();
        lblNewPass = new javax.swing.JLabel();
        txtNewPass = new javax.swing.JPasswordField();
        txtConfirm = new javax.swing.JPasswordField();
        lblConfirm = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        btnSubmit = new javax.swing.JButton();

        setTitle("Change Password");
        setToolTipText("");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon.png"))); // NOI18N

        lblOldPass.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblOldPass.setForeground(new java.awt.Color(0, 51, 255));
        lblOldPass.setText("Old Password");

        txtOldPass.setForeground(new java.awt.Color(0, 102, 51));

        lblNewPass.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblNewPass.setForeground(new java.awt.Color(0, 51, 255));
        lblNewPass.setText("New Password");

        txtNewPass.setForeground(new java.awt.Color(0, 102, 51));

        txtConfirm.setForeground(new java.awt.Color(0, 102, 51));

        lblConfirm.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblConfirm.setForeground(new java.awt.Color(0, 51, 255));
        lblConfirm.setText("Confirm");

        btnCancel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancel.setForeground(new java.awt.Color(0, 51, 51));
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/quit.png"))); // NOI18N
        btnCancel.setText("Cancel");
        btnCancel.setBorderPainted(false);
        btnCancel.setContentAreaFilled(false);
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSubmit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnSubmit.setForeground(new java.awt.Color(0, 51, 51));
        btnSubmit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Submit.png"))); // NOI18N
        btnSubmit.setText("Submit");
        btnSubmit.setBorderPainted(false);
        btnSubmit.setContentAreaFilled(false);
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnSubmit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancel)
                .addGap(19, 19, 19))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblConfirm)
                    .addComponent(lblNewPass)
                    .addComponent(lblOldPass))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtNewPass, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                    .addComponent(txtOldPass, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtConfirm, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(28, 28, 28))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblOldPass)
                    .addComponent(txtOldPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNewPass)
                    .addComponent(txtNewPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblConfirm)
                    .addComponent(txtConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSubmit)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        if (new String(txtNewPass.getPassword()).equalsIgnoreCase(new String (txtConfirm.getPassword()))) {
            getAuthority();
            
            String sql = "SELECT * FROM Account WHERE UserName = ?";
            param.clear();
            param.add(User);
            
            dc.rs = dc.prepareSelect(dc.preSt_checkPass, sql, param);
            try {
                dc.rs.next();
                if (dc.rs.getString("Password").equalsIgnoreCase(new String(txtOldPass.getPassword()))) {
                    sql = "UPDATE Account SET Password = ? WHERE UserName = ?";
                    param.clear();
                    param.add(new String(txtNewPass.getPassword()));
                    param.add(User);
                    
                    dc.prepareUpdate(dc.preSt_changePass, sql, param);
                    JOptionPane.showMessageDialog(this, "Password has been changed. Please login again.");
                    logOut();
                } else {
                    JOptionPane.showMessageDialog(this, "Password was wrong. Try again.");
                    txtOldPass.grabFocus();
                    txtOldPass.select(0, new String(txtOldPass.getPassword()).length());
                }
            } catch (SQLException ex) {
                Logger.getLogger(FrmChangePass.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(this, "New password and confirm are not matched. Try again.");
            txtNewPass.grabFocus();
            txtNewPass.select(0, new String(txtNewPass.getPassword()).length());
        }
    }//GEN-LAST:event_btnSubmitActionPerformed

    private void logOut() {
        try {
            Method logOut;
            logOut = getDesktopPane().getTopLevelAncestor().getClass().getMethod("logOut");
            logOut.invoke(getDesktopPane().getTopLevelAncestor());
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(FrmChangePass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JLabel lblConfirm;
    private javax.swing.JLabel lblNewPass;
    private javax.swing.JLabel lblOldPass;
    private javax.swing.JPasswordField txtConfirm;
    private javax.swing.JPasswordField txtNewPass;
    private javax.swing.JPasswordField txtOldPass;
    // End of variables declaration//GEN-END:variables
}
